package cn.fuxi2022.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * <p>
 * 处理跨域
 * 统一解决跨域问题
 * 统一配置之后再每个Controller中就不用在加注解了
 * </p>
 *
 * @author qy
 * @since 2019-11-21
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*"); // 运行那些请求方式访问
        config.addAllowedOrigin("*"); // 允许那些域访问
        config.addAllowedHeader("*"); // 访问时运行请求头中携带那些参数
        config.setAllowCredentials(true); // 是否允许浏览器读取response的内容

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config); // 跨域对那些请求地址有效

        return new CorsWebFilter(source);
    }
}